/*
 * @Author: sunzhijun 
 * @Date: 2019-04-18 14:41:18 
 * @Last Modified by: sunzhijun
 * @Last Modified time: 2020-03-23 16:55:48
 */
import {print, toast} from 'nc-lightapp-front';
import CommonAction from './common';
import nodeRefs from '../container/functions/nodeRefs';
import formDownload from 'src/hrpub/common/utils/download/download';
import deepCopy from 'src/hrpub/common/utils/deep-copy';
import getSysConf from "./getSysConf";
import {unZipAndDecryptForForm} from "../../../../hrpub/common/utils/unZipAndDecrypt";
import language from "../../keypersonmanage/language";

export default class HeaderAction extends CommonAction {
// export default class HeaderAction {
    constructor(comp) {
        super();
        this.comp = comp;
        this.dispatch = this.comp.props.dispatch;
    }

    // 返回
    back = async () => {
        const {props: {main: {language, isEdit}, editTable, form}, action} = this.comp;
        if (!isEdit) { //非编辑态
            this.backHomeList();
        } else {
            action.cardAct.cancel();
        }
    }

    //返回首页
    backHomeList = async () => {
        const {props, action} = this.comp;
        const {editTable, main, button, cardTable} = props;
        let {isChecked, areaCodeList} = main;
        await this.dispatch({
            type: 'main/update',
            payload: {
                isCardForm: false,
                isSort: false
            }
        });
        // 清空子表数据
        areaCodeList.map((item) => {
            // if (item !== 'hi_psndoc_cert') {
                //需要清空表格数据
                cardTable.setTableData(item, {rows: []}, null, false);
            // }
        });
        button.setButtonVisible({
            Edit: false
        })
        action.tableAct.getMainTableData();
        if (isChecked) {
            this.setShowOrHidden(isChecked);
        }
    }

    //批量修改
    batchEdit = async () => {
        const {props} = this.comp;
        const {editTable} = props;
        const {getCheckedRows} = editTable;
        let selectedRowsData = getCheckedRows('poi_list');
        await this.dispatch({
            type: 'main/update',
            payload: {
                selectedRows: selectedRowsData
            }
        })
        nodeRefs.refs.getBatchTemplateData();
    }

    //批量修改更新state值得方法
    updateState = async (batchEditModalVisible, callback) => {
        await this.dispatch({
            type: 'main/update',
            payload: {
                ...batchEditModalVisible
            }
        })
    }

    //终止关系
    termination = () => {
        const {props, action} = this.comp;
        const {form, main} = props;
        this.dispatch({
            type: 'main/update',
            payload: {
                terminationModalVisible: true
            }
        });
        form.setFormStatus('stopPoi', 'edit');
        form.setFormItemsValue('stopPoi', {'endDate': {value: main.defaultTime}});
        action.tableAct.getCardDetailData(main.pk_psnjob, 'isTermination');
    }

    // 打开查询
    query = async () => {
        const {props} = this.comp;
        props.search.openAdvSearch('query', true);
    }

    // 查询数据
    searchData = () => {
        const {props, action} = this.comp;
        const {dispatch, search} = props;
        let getConditions = search.getQueryInfo('query', true);
        dispatch({
            type: 'main/update',
            payload: {
                conditions: getConditions,
                oid: getConditions.oid
            }
        })
        action.tableAct.getMainTableData(getConditions);
    }

    //新增人员唯一性信息
    add = async () => {
        const {props, action} = this.comp;
        const {main, meta, form} = props;
        let res = await this.dispatch({
            type: 'main/getUniqueTemp'
        });
        if (res.success) {
            let temp = res.data && res.data.templateInfo;
            let fields = res.data.uniqueFields;
            let uniqueTemp = {
                uniqueTemp: temp
            }
            await meta.addMeta(uniqueTemp);
            form.setFormStatus('uniqueTemp', 'add');
            await this.dispatch({
                type: 'main/update',
                payload: {
                    isModalVisible: true,
                    uniqueFields: fields,
                    isEdit: true,
                    ui_state: 1,
                    imageData: null
                }
            });
        }

    }


    //Card 翻页操作
    handlePageChange = async (props, pks) => {
        const {main} = props;
        await this.dispatch({
            type: 'main/update',
            payload: {
                pk_dimension: pks
            }
        })
        this.setCardData(true);
    }


    //设置子集显示隐藏
    setShowOrHidden = async (v) => {
        const {props, action} = this.comp;
        let {main} = props;
        if (!!v) {
            if(!main.flag) {
                props.use && props.use.editTable(...main.subTables)
                this.dispatch({
                    type: 'main/update',
                    payload: {
                        flag: true
                    }
                });
            }
            await action.tableAct.getCardDetailData(main.pk_psnjob);
            await this.dispatch({
                type: 'main/update',
                payload: {
                    conHeight: '70%'
                }
            });
        } else {
            await this.dispatch({
                type: 'main/update',
                payload: {
                    conHeight: '100%'
                }
            });
        }

        this.dispatch({
            type: 'main/update',
            payload: {
                isChecked: !!v,
                isShowSub: !!v
                // footerHeight: footerHeight
            }
        });
    }

    // 获取初始页面高度
    getPageHeight = async () => {
        const {props} = this.comp;
        const {
            dispatch
        } = props;
        let height = '100%';
        const pageHeight = document.querySelector('.main-page');
        pageHeight && (height = (parseInt(getComputedStyle(pageHeight)['height']) - 54) + 'px');
        dispatch({
            type: 'main/update',
            payload: {
                conHeight: height,
                initHeight: height
            }
        });
    }

    //获取组织信息
    searchOrganization = async (v) => {
        const {props, action} = this.comp;
        const {dispatch, editTable, main} = props;
        const {tableId} = main;

        let arr = Object.keys(v);
        dispatch({
            type: 'main/update',
            payload: {
                orgValue: v,
                pk_org: v.refpk
            }
        });
        await getSysConf.call(this, v);
        if (!!arr.length) {
            action.treeAct.getTreeData();
            action.btnAct.orgButtonNoDataStatus();
        } else {
            action.treeAct.customTree();
            dispatch({
                type: 'main/update',
                payload: {
                    isDisabled: true
                }
            });
        }
        editTable.setTableData(tableId, {rows: []});
        this.setShowOrHidden(false);
    }

    //身故处理校验
    dieCheckAction = async () => {
        const {props} = this.comp;
        const {main} = props;
        const {language} = main;
        let res = await this.dispatch({
            type: 'main/dieCheckAction',
            payload: {
                isInJob: true,
                pk_org: main.pk_org,
                pk_psnjob: main.pk_psnjob
            }
        });
        if (res.success) {
            let data = res.data;
            let passawayData = data.passaway;
            this.promptBox({
                color: "warning",
                // title: language['hrp6003-000005'],
                // content: language['hrp6003-0000022'],
                title: language['hi6007-000004'],
                content: language['hi6007-000157'],
                beSureBtnClick: () => {
                    this.showDieModal(passawayData);
                }
            });
        }
    }
    //显示身故处理弹窗
    showDieModal = (data) => {
        const {props} = this.comp;
        const {form} = props;
        form.setAllFormValue({'passaway': data});
        form.setFormStatus('passaway', 'edit');
        this.dispatch({
            type: 'main/update',
            payload: {
                dieModalVisible: true
            }
        })
    }
    //身故处理
    dieAction = async () => {
        const {props} = this.comp;
        const {main, form} = props;
        const {language} = main;
        let formData = form.getAllFormValue('passaway');
        if (!form.isCheckNow('passaway')) {
            return false;
        }
        let res = await this.dispatch({
            type: 'main/dieAction',
            payload: {
                isInJob: true,                  //是否在职
                model: formData,                        //表单数据
                pk_org: main.pk_org,            //主组织
                pk_psnjob: main.pk_psnjob       //主表中行选择的主键
            }
        })
        if (res.success) {
            let data = res.data;
            if (data === 'success') {
                this.toast({color: 'success', content: language['hi6007-000158']});
                this.hiddenModal();
            } else {
                this.toast({color: 'danger', content: language['hi6007-000289']});
            }
        }
    }

    //隐藏身故处理Modal
    hiddenModal = () => {
        const {props} = this.comp;
        this.dispatch({
            type: 'main/update',
            payload: {
                dieModalVisible: false
            }
        })
    }

    //设置排序弹出显隐性
    sortModalVisible = () => {
        const {props} = this.comp;
        const {main} = props;
        this.dispatch({
            type: 'main/update',
            payload: {
                sortModalVisible: !main.sortModalVisible
            }
        })
    }

    //导出照片
    exportPhoto = async () => {
        const {props} = this.comp;
        const {main, editTable} = props;
        const {language} = main;
        let checkedRowsData = editTable.getCheckedRows(main.tableId);
        let pk_psnjobArr = [];
        !!checkedRowsData.length && checkedRowsData.map((item, index) => {
            pk_psnjobArr.push(item.data.values.pk_psnjob.value)
        })
        if (!!pk_psnjobArr.length) {
            let pk_psnjobStr = pk_psnjobArr.join(',');
            let postData = {
                param_str: pk_psnjobStr,
                pk_org: main.pk_org
            }

            formDownload({
                url: '/nccloud/hrhi/psndoc/PsndocExportPhotoAction.do',
                body: postData,
                enctype: 2,
                onResult: (resBody) => {
                    let innerText = resBody.innerText;
                    let res = {};
                    try {
                        res = JSON.parse(innerText);
                        if (typeof res === 'string') {
                            throw new Error();
                        }
                    } catch (e) {
                        res = unZipAndDecryptForForm(innerText);
                    }
                    if (res.success) {
                        toast({
                            color: 'success',
                            content: language['hi6007-000183'] // 上传成功
                        });
                    } else {
                        toast({
                            color: 'danger',
                            content: res.error.message
                        });
                    }
                }
            });
        } else {
            this.toast({color: 'danger', content: language['hi6007-000060']});
        }
    }

    //附件管理显示隐藏
    fileManager = async () => {
        const {props} = this.comp;
        let {main} = props;
        let {showUploader} = main;
        await this.dispatch({
            type: 'main/update',
            payload: {
                showUploader: !showUploader
            }
        })
    }

    //调整顺序
    adjustSort = async () => {
        const {props, action} = this.comp;
        let {main, syncTree, editTable} = props;
        let {isSort, tableId} = main;
        await this.dispatch({
            type: 'main/update',
            payload: {
                isSort: true,
                isEdit: true
            }
        })
        syncTree.setNodeDisable('treeid', true);
        action.btnAct.sortButtonStatus();
        editTable.hideColByKey(tableId, 'handleArea');
        editTable.showColByKey(tableId, 'showorder');
        editTable.setStatus(tableId, 'edit');
        editTable.setColEditableByKey(tableId, 'showorder', false);
    }
    //取消调整顺序
    cancelAdjustSort = async () => {
        const {props, action} = this.comp;
        let {main, syncTree, editTable} = props;
        let {tableId} = main;
        await this.dispatch({
            type: 'main/update',
            payload: {
                isSort: false,
                isEdit: false
            }
        })
        action.btnAct.cancelSortButtonStatus();
        syncTree.setNodeDisable('treeid', false);
        editTable.hideColByKey(tableId, 'showorder');
        editTable.showColByKey(tableId, 'handleArea');
        editTable.setStatus(tableId, 'browse');
        editTable.setColEditableByKey(tableId, 'showorder', true);
    }
    //批量增加子集
    batchAddSub = async () => {
        const {props, action} = this.comp;
        const {editTable, main} = props;
        const {language} = main;
        let checkedRowsData = editTable.getCheckedRows(main.tableId);
        let pk_psnjobArr = [];
        !!checkedRowsData.length && checkedRowsData.map((item, index) => {
            pk_psnjobArr.push(item.data.values.pk_psnjob.value)
        })
        if (!!pk_psnjobArr.length) {
            let pk_psnjobStr = pk_psnjobArr.join(',');
            await this.dispatch({
                type: 'main/update',
                payload: {
                    batchAddSubVisible: true,
                    pk_psnjobStr: pk_psnjobStr
                }
            })
        } else {
            this.toast({color: 'danger', content: language['hi6007-000290']}); //请选择要批量增加子集的人员!
        }
    }
    //隐藏批量增加子集弹窗
    setHiddenBatchAddSub = async () => {
        await this.dispatch({
            type: 'main/update',
            payload: {
                batchAddSubVisible: false
            }
        })
    }
    //打印
    printAction = async () => {
        const {props} = this.comp;
        const {editTable, main} = props;
        let {tableId, appConfig} = main;
        let oids = [];
        let allTableData = editTable.getAllRows(main.tableId);
        allTableData.map((item, index) => {
            oids.push(item.values.pk_psnjob.value);
        })
        print('pdf', '/nccloud/hrhi/psndoc/PsndocTemplatePrintAction.do', {
            funcode: appConfig.appcode,
            nodekey: tableId,
            oids: oids
        });
    }

    //输出
    outputAction = async () => {
        const {props} = this.comp;
        const {editTable, main} = props;
        let {tableId, appConfig} = main;
        let oids = [];
        let allTableData = editTable.getAllRows(main.tableId);
        allTableData.map((item, index) => {
            oids.push(item.values.pk_psnjob.value);
        })
        await this.dispatch({
            type: 'main/update',
            payload: {
                printData: {
                    funcode: appConfig.appcode,
                    nodekey: tableId,
                    oids: oids,
                    outputType: 'output'
                }
            }
        })
        nodeRefs.printOutputRefs.open();
    }

    //身故处理编辑前事件
    dieBeforeEvent = (props, moduleId, key, value, data) => {
        let {main: {pk_org}, meta} = props;
        if (key === 'pk_dept') {
            let metaData = meta.getMeta();
            let template = deepCopy(metaData);
            template[moduleId].items.find(item => item.attrcode === key).queryCondition = function () {
                return {
                    "pk_org": pk_org
                }
            };
            meta.setMeta(template);
        }
        return true;
    }

    // 联查卡片
    showCardview = () => {
        const {props: {editTable, main}} = this.comp;
        let {tableId} = main;
        let listData = editTable.getCheckedRows(tableId);
        // nodeRefs.showCardViewRefs.openCardViewModal(listData);
        nodeRefs.wpsview.openView(listData)
    }
}